package com.itheima.tlias.service.impl;

import com.itheima.tlias.dto.AddDeptDto;
import com.itheima.tlias.dto.UpdateDto;
import com.itheima.tlias.entity.Dept;
import com.itheima.tlias.exception.BizException;
import com.itheima.tlias.mapper.DeptMapper;
import com.itheima.tlias.mapper.EmpMapper;
import com.itheima.tlias.service.DeptService;
import com.itheima.tlias.vo.DeptVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    public List<DeptVo> depts() throws Exception {
        List<DeptVo> depts = deptMapper.depts();
        return depts;
    }

    @Override
    public void deleteDept(Integer id) {

        if (!CollectionUtils.isEmpty(empMapper.empByDeptId(id))) {
            throw new BizException("部门中还有员工，无法删除");
        }
        deptMapper.deleteDept(id);
    }

    @Override
    public void addDept(AddDeptDto dto) {
        Dept dept = new Dept();
        dept.setName(dto.getName());
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public DeptVo getById(Integer id) {
        DeptVo deptVo = deptMapper.getById(id);
        return deptVo;
    }

    @Override
    public void updateDept(UpdateDto dto) {
        Dept dept = new Dept();
        dept.setName(dto.getName());
        dept.setId(dto.getId());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateDept(dept);
    }
}
